<!--<template>-->
<!--  <div class="app-container">-->
<!--    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">-->
<!--      <el-form-item label="外文名称" prop="name1">-->
<!--        <el-input-->
<!--            v-model="queryParams.name1"-->
<!--            placeholder="请输入外文名称"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="中文名称" prop="name2">-->
<!--        <el-input-->
<!--            v-model="queryParams.name2"-->
<!--            placeholder="请输入中文名称"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="有几集" prop="have">-->
<!--        <el-input-->
<!--            v-model="queryParams.have"-->
<!--            placeholder="请输入有几集"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--            type="number"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="第几季" prop="season">-->
<!--        <el-input-->
<!--            v-model="queryParams.season"-->
<!--            placeholder="请输入第几季"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--            type="number"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="状态" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>-->
<!--          <el-option-->
<!--              v-for="dict in book_status"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="平台" prop="vendor">-->
<!--        <el-select v-model="queryParams.vendor" placeholder="请选择平台" clearable>-->
<!--          <el-option-->
<!--              v-for="dict in book_vendor"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>-->
<!--        <el-button icon="Refresh" @click="resetQuery">重置</el-button>-->
<!--      </el-form-item>-->
<!--    </el-form>-->

<!--    <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">-->
<!--      <el-table-column type="selection" width="55" align="center"/>-->
<!--      <el-table-column label="ID" align="center" prop="id"/>-->
<!--      <el-table-column label="外文名称" align="center" prop="name1"/>-->
<!--      <el-table-column label="中文名称" align="center" prop="name2"/>-->
<!--      &lt;!&ndash;      <el-table-column label="详情" align="center" prop="detail" />&ndash;&gt;-->
<!--      <el-table-column label="有几集" align="center" prop="have">-->
<!--        <template #default="scope">-->
<!--          <span v-if="scope.row.have === 0">未知</span>-->
<!--          <span v-else>{{ scope.row.have }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="第几季" align="center" prop="season">-->
<!--        <template #default="scope">-->
<!--          <span v-if="scope.row.season === 0">未知</span>-->
<!--          <span v-else>{{ scope.row.season }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->


<!--      &lt;!&ndash;      <el-table-column label="更新时间" align="center" prop="renew" />&ndash;&gt;-->
<!--      <el-table-column label="更新时间" align="center" prop="renew">-->
<!--        <template #default="scope">-->
<!--          <div v-for="(time, index) in jsonParse(scope.row.renew)" :key="index">-->
<!--            {{ weekdays[time.day] }} <br/> {{ time.clock }}-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      &lt;!&ndash;      <el-table-column label="链接" align="center" prop="url" />&ndash;&gt;-->
<!--      <el-table-column label="链接" align="center" prop="url">-->
<!--        <template #default="scope">-->
<!--          <div v-for="(url, index) in jsonParse(scope.row.url)" :key="index">-->
<!--            <el-button @click="openUrl(url.url)">{{ url.name }}</el-button>-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="状态" align="center" prop="status">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="book_status" :value="scope.row.status"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="平台" align="center" prop="vendor">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="book_vendor" :value="scope.row.vendor"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="图片" align="center" prop="picture" width="100" v-if="isImageUpload">-->
<!--        <template #default="scope">-->
<!--          <image-preview :src="scope.row.picture" :width="50" :height="50" preview-teleported/>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="图片地址" align="center" prop="pictureUrl" v-if="isImageURL" width="100">-->
<!--        <template #default="scope">-->
<!--          <image-preview :src="scope.row.pictureUrl" :width="100" :height="100" preview-teleported/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="修改时间" align="center" prop="reTime" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.reTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="备注" align="center" prop="remark"/>-->

<!--    </el-table>-->

<!--    <pagination-->
<!--        v-show="total>0"-->
<!--        :total="total"-->
<!--        v-model:page="queryParams.pageNum"-->
<!--        v-model:limit="queryParams.pageSize"-->
<!--        @pagination="getList"-->
<!--    />-->

<!--    </div>-->
<!--</template>-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="外文名称" prop="name1">
              <el-input
                  v-model="queryParams.name1"
                  placeholder="请输入外文名称"
                  clearable
                  @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="中文名称" prop="name2">
              <el-input
                  v-model="queryParams.name2"
                  placeholder="请输入中文名称"
                  clearable
                  @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="有几集" prop="have">
              <el-input
                  v-model="queryParams.have"
                  placeholder="请输入有几集"
                  clearable
                  @keyup.enter="handleQuery"
                  type="number"
              />
            </el-form-item>
            <el-form-item label="第几季" prop="season">
              <el-input
                  v-model="queryParams.season"
                  placeholder="请输入第几季"
                  clearable
                  @keyup.enter="handleQuery"
                  type="number"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option
                    v-for="dict in book_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="平台" prop="vendor">
              <el-select v-model="queryParams.vendor" placeholder="请选择平台" clearable>
                <el-option
                    v-for="dict in book_vendor"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
    <el-row :gutter="20">
      <el-col :span="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="item in bookList" :key="item.id">
        <el-card shadow="hover" style="margin-bottom: 20px;">
          <!--          {{item}}-->
          <div slot="header" style="text-align: center">
            <span style="font-size: 20px;font-weight: bold">{{ item.name2 + ((item.season === 0 || item.season ===1 || item.season === null) ? '' : '[第' + item.season + '季]')}}</span>
            <p>{{item.name1 === null? '' : item.name1  +((item.season === 0 || item.season ===1 || item.season === null) ? '' : '-[S' + item.season + ']')}}</p>
          </div>
          <div style="text-align: center;">
            <image-preview v-if="item.picture || item.pictureUrl" :src="item.picture ? item.picture : item.pictureUrl" width="100" height="100" preview-teleported/>
            <p>{{ (item.have || item.have > 0) ? '有'+item.have+'集' : ''  }} </p>
            <el-button-group style="margin-bottom: 10px;">
              <el-button v-for="(url, index) in jsonParse(item.url)" :key="index" @click="openUrl(url.url)">
                {{ url.name }}
              </el-button>
            </el-button-group>
            <br>
            <dict-tag :options="book_status" :value="item.status" style="display: inline;"/> <nbsp/>
            <dict-tag :options="book_vendor" :value="item.vendor" style="display: inline;"/>
            <br>
            <!--            <p>状态: {{ getStatus(item.status) }}</p>-->
            <!--            <p>平台: {{ getVendor(item.vendor) }}</p>-->
            <template v-if="item.status === 2">
              <p v-for="(time, index) in jsonParse(item.renew)" :key="index">
                {{ weekdays[time.day] }} <nbsp/> {{ time.clock }} <br/>
              </p>
            </template>
            <!--            {{ item.detail }}-->
          </div>
        </el-card>
      </el-col>
      <!--    {{animationList}}-->
    </el-row>
        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
  </div>
</template>
<script setup name="Book">
import {listBook, getBook, delBook, addBook, updateBook} from "@/api/type/book";
import {getConfigKey} from "@/api/system/config";

const {proxy} = getCurrentInstance();
const {book_vendor, book_status} = proxy.useDict('book_vendor', 'book_status');

const bookList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeReTime = ref([]);
const activeTab = ref('basicInfo'); // 默认激活的标签页
const isImageUpload = ref(false); //是否允许上传图片
const isImageURL = ref(false);  //是否允许输入图片地址
getConfigKey("info.image.upload").then(res => {
  isImageUpload.value = res.msg === 'true';
})
getConfigKey("info.image.url").then(res => {
  isImageURL.value = res.msg === 'true';
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: null,
    pageSize: null,
    name1: null,
    name2: null,
    detail: null,
    have: null,
    season: null,
    status: null,
    vendor: null,
  },
  rules: {
    name2: [
      {required: true, message: "中文名称不能为空", trigger: "blur"}
    ],
    have: [
      {
        validator: (rule, value, callback) => {
          if (value < 0) {
            callback(new Error('请输入一个大于等于零的数'));
          } else {
            callback(); // 通过验证
          }
        },
        trigger: 'blur'
      }
    ],
    season: [
      {
        validator: (rule, value, callback) => {
          if (value < 0) {
            callback(new Error('请输入一个大于等于零的数'));
          } else {
            callback(); // 通过验证
          }
        },
        trigger: 'blur'
      }
    ],
    vendor: [
      {required: true, message: "平台不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);


// 周几的键值对
const weekdays = {
  1: "周一",
  2: "周二",
  3: "周三",
  4: "周四",
  5: "周五",
  6: "周六",
  7: "周日"
};


/** 查询书籍列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeReTime && '' != daterangeReTime) {
    queryParams.value.params["beginReTime"] = daterangeReTime.value[0];
    queryParams.value.params["endReTime"] = daterangeReTime.value[1];
  }
  listBook(queryParams.value).then(response => {
    bookList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}


// 表单重置
function reset() {
  form.value = {
    id: null,
    name1: null,
    name2: null,
    detail: null,
    have: null,
    season: null,
    renew: [{}],
    url: [{}],
    status: null,
    vendor: null,
    picture: null,
    pictureUrl: null,
    reTime: null,
    remark: null
  };
  proxy.resetForm("bookRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeReTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  activeTab.value = 'basicInfo';
  open.value = true;
  title.value = "添加书籍";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  activeTab.value = 'basicInfo';
  const _id = row.id || ids.value
  getBook(_id).then(response => {
    form.value = response.data;
    open.value = true;
    form.value.renew = JSON.parse(response.data.renew);
    form.value.url = JSON.parse(response.data.url);
    title.value = "修改书籍";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bookRef"].validate(valid => {
    if (valid) {
      form.value.renew = JSON.stringify(form.value.renew);
      form.value.url = JSON.stringify(form.value.url);
      if (form.value.id != null) {
        updateBook(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBook(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除书籍编号为"' + _ids + '"的数据项？').then(function () {
    return delBook(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('type/book/export', {
    ...queryParams.value
  }, `book_${new Date().getTime()}.xlsx`)
}

const addTime = () => {
  // console.log(typeof form.value.renew);
  // 确保 form.renew 是数组
  if (!Array.isArray(form.value.renew)) {
    form.renew = [{}];
  }
  form.value.renew.push({day: '', clock: ''});
  // console.log('New time added:', form.value.renew);
};


// 删除更新时间
const removeTime = (index) => {
  // 确保 form.renew 是数组
  if (!Array.isArray(form.value.renew)) {
    return;
  }
  form.value.renew.splice(index, 1);
};

const addURL = () => {
  // 确保 form.url 是数组
  if (!Array.isArray(form.value.url)) {
    form.url = [{}];
  }
  form.value.url.push({name: '', url: ''});
  // console.log('New url added:', form.value.url);
};


// 删除URL
const removeURL = (index) => {
  if (!Array.isArray(form.value.url)) {
    return;
  }
  form.value.url.splice(index, 1);
};

// 将 JSON 字符串转换为 JSON 对象
function jsonParse(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    // console.error("Failed to parse JSON:", error);
    return [{}];
  }
}

function openUrl(url) {
  if (url) {
    window.open(url, '_blank');
  }
}

getList();
</script>
